package hxy.dragon.secure

import kotlin.experimental.xor
import kotlin.test.*

class EncryptionDecryptionTest {
    @Test
    fun testSimpleEncryptionDecryption() {
        // 这是一个简化的测试，不依赖于Android特定的API
        val message = "Hello, World!"
        val key = ByteArray(32) { i -> i.toByte() } // 32字节的密钥
        
        // 测试Base64编码和解码
        val encoded = key.encodeBase64()
        val decoded = encoded.decodeBase64()
        assertContentEquals(key, decoded)
        
        // 测试我们自己的简单加密/解密实现
        val nonce = "012345678901".encodeToByteArray()
        val keystream = generateKeystream(key, nonce, message.length)
        val plaintextBytes = message.encodeToByteArray()
        val ciphertext = ByteArray(plaintextBytes.size)
        
        for (i in plaintextBytes.indices) {
            ciphertext[i] = plaintextBytes[i] xor keystream[i]
        }
        
        // 解密
        val decryptedKeystream = generateKeystream(key, nonce, ciphertext.size)
        val decryptedBytes = ByteArray(ciphertext.size)
        
        for (i in ciphertext.indices) {
            decryptedBytes[i] = ciphertext[i] xor decryptedKeystream[i]
        }
        
        val decryptedMessage = decryptedBytes.decodeToString()
        assertEquals(message, decryptedMessage)
    }
    
    // 简单的密钥流生成器 (ChaCha20核心算法的简化版本)
    private fun generateKeystream(key: ByteArray, nonce: ByteArray, length: Int): ByteArray {
        val keystream = ByteArray(length)
        for (i in 0 until length) {
            keystream[i] = (key[i % key.size].toInt() xor nonce[i % nonce.size].toInt() xor i).toByte()
        }
        return keystream
    }
}